const { ipcMain, BrowserWindow } = require('electron')
const fs = require('fs/promises')
const path = require('path')

const getSource = (url) => {
  return new Promise((resolve, reject) => {
    const win = new BrowserWindow({
      width: 500,
      height: 500,
      show: false,
      webPreferences: {
        offscreen: true
      }
    })

    win.loadURL(url)
    win.webContents.on('did-finish-load', async () => {
      const title = win.getTitle()
      try {
        // nativeImage
        const image = await win.webContents.capturePage()
        if (!image.isEmpty()) {
          const screenshot = image.toDataURL()
          resolve({
            title,
            screenshot,
            url
          })
        } else {
          resolve({
            msg: '无法访问该站点。'
          })
        }
      } catch (e) {
        reject(e)
      }
    })
  })
}

const readImgsFiles = async () => {
  // console.log('222');
  // 读取指定文件的所有图片
  const files = await fs.readdir(path.resolve(__dirname, '../public/uploads/'))
  return files 
}

ipcMain.handle('on-url-event', async (e, url) => {
  const result = await getSource(url)
  return result
})
ipcMain.handle('on-readImgs-event', (e, msg) => {
  return readImgsFiles()
})